<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Authentication {
	private $CI;
	
	public function __construct() {
		$this->CI = &get_instance();
		$this->CI->load->model('Authentication_Model', 'authenticationmodel');
	}

	public function login($username, $password) {
		$userinfo = $this->CI->authenticationmodel->login($username, $password); 
		if ($userinfo === NULL) {
			return FALSE;
		} else {
			$this->CI->session->set_userdata('username', $userinfo->username);
			$this->CI->session->set_userdata('role', $userinfo->role);
			return TRUE;
		}
	}
	
	public function logout() {
		$this->CI->session->unset_userdata('username');
		$this->CI->session->unset_userdata('role');
		$this->CI->session->sess_destroy();
	}
	
	public function get_current_user() {
		if ($this->is_loggedin() === FALSE) {
			return NULL;
		} else {
			$userinfo = array(
				'username' => $this->CI->session->userdata('username'),
				'role' => $this->CI->session->userdata('role')
			);
			return $userinfo;
		}
	}
	
	public function is_allowed($privilege) {
		if ($this->is_loggedin() === FALSE) {
			return FALSE;
		} else {
			$role = $this->CI->session->userdata('role');
			return $this->CI->authenticationmodel->is_allowed($role, $privilege);
		}
	}
	
	public function is_loggedin() {
		$user = $this->CI->session->userdata('username');
		if ($user === FALSE) {
			return FALSE;
		} else {
			return TRUE;
		}
	}
}